package cn.ljserver.project.webOfficeImpl;

import cn.ljserver.project.entity.File;
import cn.ljserver.project.entity.User;
import cn.ljserver.project.service.FileService;
import cn.ljserver.project.service.QnFileService;
import cn.ljserver.project.service.UserService;
import cn.ljserver.tool.weboffice.v3.exception.FileNotExist;
import cn.ljserver.tool.weboffice.v3.exception.FileUploadNotComplete;
import cn.ljserver.tool.weboffice.v3.model.FileInfo;
import cn.ljserver.tool.weboffice.v3.model.FileUploadSinglePhase;
import cn.ljserver.tool.weboffice.v3.service.SinglePhaseFileStorageService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 单阶段文件保存接口
 * <p>
 * <a href="https://solution.wps.cn/docs/callback/save.html#%E5%8D%95%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">详见wps web office官网</a>
 */
@Service
public class SinglePhaseFileStorageServiceImpl implements SinglePhaseFileStorageService {
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param request 上传文件请求
     * @return 文件信息
     * <p>
     * <a href="https://solution.wps.cn/docs/callback/save.html#%E5%8D%95%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">详见wps web office官网</a>
     */
    @Override
    public FileInfo uploadFile(FileUploadSinglePhase.Request request) {
        // 获取用户信息 -> 这个方法点进去看看 ？？！！
        final User user = userService.fetchUserByToken();

        // 保存文件信息
        final File file = Optional.of(request)
                .map(r -> fileService.fetchFile(request.getFileId()))
                .map(f -> File.builder()
                        .id(f.getId().copyForNewVersion())
                        .creator(f.getCreator())
                        .createTime(f.getCreateTime())
                        .modifyTime(LocalDateTime.now())
                        .modifier(user)
                        .name(request.getName())
                        .size(request.getSize())

                        // 上传文件获取到URL
                        // --------------------------------
                        // 这里不应该直接保存URL，而是不带domain的uri方便后续迁移等等
                        // 为了方便，就这么弄了
                        // --------------------------------

                        .url(QnFileService.upload(request.getFile()))
                        .build())
                .map(f -> fileService.repository().save(f))
                .orElseThrow(FileNotExist::new);

        // 返回文件信息
        return file.toFileInfo();
    }
}
